
package springboot.springboot06_ssmp.controller;

        import cn.hutool.core.date.DateUtil;
        import cn.hutool.core.lang.UUID;
        import com.baomidou.mybatisplus.core.metadata.IPage;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.beans.factory.annotation.Value;
        import org.springframework.web.bind.annotation.*;
        import org.springframework.web.multipart.MultipartFile;
        import springboot.common_utils.POIUtils;
        import springboot.common_utils.R;

        import springboot.springboot06_ssmp.entity.Images;
        import springboot.springboot06_ssmp.entity.SendBack;
        import springboot.springboot06_ssmp.service.IImagesService;
        import springboot.springboot06_ssmp.service.ISendBackService;

        import java.time.LocalDate;
        import java.io.IOException;
        import java.nio.file.Files;
        import java.nio.file.Path;
        import java.nio.file.Paths;
        import java.text.ParseException;
        import java.text.SimpleDateFormat;
        import java.time.LocalDate;
        import java.util.ArrayList;
        import java.util.Date;
        import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author daiqiang
 * @since 2024-01-24
 */
@RestController
@RequestMapping("sendBack")
public class SendBackController {
    @Autowired
    private ISendBackService sendBackService;

    @Autowired
    private IImagesService imagesService;

    @Value("${file.upload.path}")
    private String uploadPath;
    @GetMapping
    public R getAll(){
        return R.success(sendBackService.list());
    }
    @PostMapping
    public R save(@RequestBody SendBack sendBack) {

        try {
            sendBackService.save(sendBack);
            return R.success("success");
        } catch (Exception e) {

            return R.fail("fail");
        }
    }
    @PutMapping
    public  R update(@RequestBody SendBack sendBack){
        System.out.println("----》"+sendBack);
        return  R.success(sendBackService.updateById(sendBack));
    }
    @DeleteMapping("{id}")
    public  R delete(@PathVariable Integer id){
        return  R.success(sendBackService.removeById(id));
    }
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        System.out.println("参数----》"+id);
        if(sendBackService.getById(id)==null){
            return  R.fail("id不存在");
        }

        return  R.success(sendBackService.getById(id));
    }


    @GetMapping("{currentPage}/{pageSize}")
    public R getAllPage(@PathVariable int currentPage, @PathVariable int pageSize, SendBack sendBack){
        System.out.println("参数----》"+sendBack);
        IPage<SendBack> pagesendBack=sendBackService.getPage(currentPage,pageSize,sendBack );
        return R.success(pagesendBack);

    }
    //图片上传
    @RequestMapping("/upload")
    public R upload(@RequestParam("imgFile") MultipartFile imgFile){

        if (imgFile.isEmpty()) {
            return R.fail("File is empty");
        }
        try{
            // 获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            // 获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf - 1);
            // 使用UUID随机产生文件名称，防止同名文件覆盖
            String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
            byte[] bytes = imgFile.getBytes();
            Path path = Paths.get(uploadPath, fileName);
            Files.write(path, bytes);
            Images images = new Images();
            images.setName(fileName);
            images.setPath(String.valueOf(path));
            //保存图片信息到数据库
            boolean flag =imagesService.save(images);
            if (flag){
                return R.success(2000,"上传成功！", fileName);
            }else {
                return R.fail(2001,"上传失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
            //图片上传失败
            return R.fail(false,"上传失败！");
        }
    }
    //云存储方案
    /*public R upload(@RequestParam("imgFile") MultipartFile imgFile){
        private String uploadPath;
        try{
            //获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf - 1);
            //使用UUID随机产生文件名称，防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            QiniuUtils.upload2Qiniu(Arrays.toString(imgFile.getBytes()),fileName);
            //图片上传成功
           *//* R result = new R(true, "上传成功！");
            result.setData(fileName);*//*
            return R.success(2000,fileName);
        }catch (Exception e){
            e.printStackTrace();
            //图片上传失败
            return new R(false,"上传失败！");
        }
    }*/
    /**
     * Excel文件上传，并解析文件内容保存到数据库
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload2")
    public R upload2(@RequestParam("excelFile")MultipartFile excelFile) throws IOException {
        try {
            //读取Excel文件数据
            List<String[]> list = POIUtils.readExcel(excelFile);
            System.out.println(list);
            if(list != null && list.size() > 0){
                List<SendBack> SendBackList = new ArrayList<>();
                for (String[] strings : list) {
                    SendBack sendBack = new SendBack();
                    sendBack.setName(strings[0]);
                    sendBack.setSex(strings[1]);
                    sendBack.setAge(Integer.parseInt(strings[2]));
                    sendBack.setAddress(strings[3]);
                    // 假设 strings[4] 是从Excel读取的日期字符串 "2024/3/1"
                    String dateString = strings[4]; // "2024/3/1"
                    String dateString2 = strings[6]; // "2024/3/1"
                    // 使用 SimpleDateFormat 来解析日期字符串并创建一个 Date 对象
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                    Date sendDate = dateFormat.parse(dateString);
                    Date backdate = dateFormat.parse(dateString2);
                    sendBack.setSenddate(sendDate);
                    sendBack.setSendprice(Integer.parseInt(strings[5]));
                    sendBack.setBackdate(backdate);
                    sendBack.setBackprice(Integer.parseInt(strings[7]));
                    sendBack.setRemark(strings[8]);
                    SendBackList.add(sendBack);
                }
                sendBackService.add(SendBackList);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail("上传失败！");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return R.success("上传成功！");
    }

}
